、<template>
  <div class="role-management-container">
    <!-- 搜索栏 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="searchForm.roleKey" placeholder="请输入权限字符"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="启用" value="0"></el-option>
            <el-option label="禁用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <div class="table-header">
      <el-button type="primary" @click="handleAdd">添加</el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">批量删除</el-button>
    </div>

    <!-- 角色表格 -->
    <el-table
      ref="multipleTableRef"
      v-loading="tableLoading"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="roleId" label="角色ID" width="80"></el-table-column>
      <el-table-column prop="roleName" label="角色名称"></el-table-column>
      <el-table-column prop="roleKey" label="权限字符"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="createByName" label="创建人"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
          <el-button size="small" type="primary" @click="handlePermission(scope.row)">权限</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>

    <!-- 添加/编辑角色弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加角色' : '修改角色'">
      <el-form ref="roleFormRef" :model="roleForm" :rules="roleRules" label-width="120px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="roleForm.roleKey" placeholder="请输入权限字符"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="roleForm.status" placeholder="请选择状态">
            <el-option label="启用" :value="0"></el-option>
            <el-option label="禁用" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="roleForm.remark" type="textarea" rows="4" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 权限配置弹窗 -->
    <el-dialog v-model="permissionDialogVisible" title="权限配置" width="60%">
      <el-tree
        ref="menuTreeRef"
        :data="menuData"
        :props="treeProps"
        show-checkbox
        node-key="menuId"
        :default-checked-keys="checkedMenuKeys"
        check-strictly
      ></el-tree>
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePermissions">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox, ElForm, ElTable, ElTree } from 'element-plus';
import type { FormInstance, FormRules, TreeInstance } from 'element-plus';
import {
  getRoles,
  addRole,
  updateRole,
  deleteRole,
  getRolePermissions,
  saveRolePermissions,
  getAllMenus
} from '@/api/role';
import type { Role, RoleForm, Menu, RoleQueryParams } from '@/types/role';

// 搜索表单
const searchForm = reactive({
  roleName: '',
  roleKey: '',
  status: ''
});

// 表格数据
const tableData = ref<Role[]>([]);
const tableLoading = ref(false);
const multipleSelection = ref<Role[]>([]);
const multipleTableRef = ref<InstanceType<typeof ElTable>>();

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
});

// 弹窗控制
const dialogVisible = ref(false);
const permissionDialogVisible = ref(false);
const dialogType = ref<'add' | 'edit'>('add');

// 表单
const roleFormRef = ref<FormInstance>();
const roleForm = reactive<RoleForm>({
  roleId: 0,
  roleName: '',
  roleKey: '',
  status: 0,
  remark: ''
});

// 表单验证规则
const roleRules = reactive<FormRules>({
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '角色名称长度必须在2-50个字符之间', trigger: 'blur' }
  ],
  roleKey: [
    { required: true, message: '请输入权限字符', trigger: 'blur' },
    { min: 1, max: 100, message: '权限字符长度必须在1-100个字符之间', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
});

// 权限配置
const menuTreeRef = ref<TreeInstance>();
const menuData = ref<Menu[]>([]);
const checkedMenuKeys = ref<number[]>([]);
const currentRoleId = ref(0);
const treeProps = {
  children: 'children',
  label: 'menuName'
};

// 生命周期
onMounted(() => {
  fetchRoles();
});

// 获取角色列表
const fetchRoles = async () => {
  tableLoading.value = true;
  try {
    const params: RoleQueryParams = {
      roleName: searchForm.roleName,
      roleKey: searchForm.roleKey,
      status: searchForm.status,
      start: (pagination.current - 1) * pagination.pageSize,
      pageSize: pagination.pageSize
    };

    console.log('请求参数:', params);

    const res = await getRoles(params);
    console.log('响应数据:', res);

    if (res.code === 200) {
      tableData.value = res.data.list || [];
      pagination.total = res.data.total || 0;

      // 确保状态值是数字类型
      tableData.value.forEach(item => {
        if (typeof item.status === 'string') {
          item.status = item.status === '0' ? 0 : 1;
        }
      });
    } else {
      ElMessage.error(res.msg || '获取角色列表失败');
    }
  } catch (error: any) {
    console.error('请求错误:', error);
    ElMessage.error(error.response?.data?.msg || error.message || '获取角色列表失败');
  } finally {
    tableLoading.value = false;
  }
};

// 搜索和重置
const handleSearch = () => {
  pagination.current = 1;
  fetchRoles();
};

const handleReset = () => {
  searchForm.roleName = '';
  searchForm.roleKey = '';
  searchForm.status = '';
  pagination.current = 1;
  fetchRoles();
};

// 分页事件
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.current = 1;
  fetchRoles();
};

const handleCurrentChange = (val: number) => {
  pagination.current = val;
  fetchRoles();
};

// 选择事件
const handleSelectionChange = (val: Role[]) => {
  multipleSelection.value = val;
};

// 添加角色
const handleAdd = () => {
  dialogType.value = 'add';
  roleForm.roleId = 0;
  roleForm.roleName = '';
  roleForm.roleKey = '';
  roleForm.status = 0;
  roleForm.remark = '';

  nextTick(() => {
    roleFormRef.value?.clearValidate();
  });

  dialogVisible.value = true;
};

// 编辑角色
const handleEdit = (row: Role) => {
  dialogType.value = 'edit';
  roleForm.roleId = row.roleId;
  roleForm.roleName = row.roleName;
  roleForm.roleKey = row.roleKey;
  roleForm.status = row.status;
  roleForm.remark = row.remark || '';

  nextTick(() => {
    roleFormRef.value?.clearValidate();
  });

  dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  if (!roleFormRef.value) return;

  try {
    await roleFormRef.value.validate();

    if (dialogType.value === 'add') {
      await addRole(roleForm);
      ElMessage.success('添加角色成功');
    } else {
      await updateRole(roleForm);
      ElMessage.success('修改角色成功');
    }

    dialogVisible.value = false;
    fetchRoles();
  } catch (error: any) {
    if (error.name !== 'ValidationError') {
      ElMessage.error(error.response?.data?.msg ||
        (dialogType.value === 'add' ? '添加角色失败' : '修改角色失败'));
    }
  }
};

// 状态变更
const handleStatusChange = async (row: Role) => {
  try {
    await updateRole({
      roleId: row.roleId,
      roleName: row.roleName,
      roleKey: row.roleKey,
      status: row.status,
      remark: row.remark
    });
    ElMessage.success('状态更新成功');
  } catch (error: any) {
    // 回滚状态
    row.status = row.status === 0 ? 1 : 0;
    ElMessage.error(error.response?.data?.msg || '状态更新失败');
  }
};

// 权限配置
const handlePermission = async (row: Role) => {
  currentRoleId.value = row.roleId;
  permissionDialogVisible.value = true;
  await loadMenuData();
  await loadRolePermissions(row.roleId);
};

// 加载菜单数据
const loadMenuData = async () => {
  try {
    const res = await getAllMenus();
    menuData.value = buildMenuTree(res.data);
  } catch (error: any) {
    ElMessage.error(error.response?.data?.msg || '加载菜单数据失败');
  }
};

// 构建菜单树
const buildMenuTree = (menus: Menu[]): Menu[] => {
  const tree: Menu[] = [];
  const menuMap = new Map<number, Menu>();

  // 创建菜单映射
  menus.forEach(menu => {
    menuMap.set(menu.menuId, { ...menu, children: [] });
  });

  // 构建树结构
  menus.forEach(menu => {
    const node = menuMap.get(menu.menuId);
    if (node) {
      if (menu.parentId === 0) {
        tree.push(node);
      } else {
        const parent = menuMap.get(menu.parentId);
        if (parent && parent.children) {
          parent.children.push(node);
        }
      }
    }
  });

  return tree;
};

// 加载角色权限
const loadRolePermissions = async (roleId: number) => {
  try {
    const res = await getRolePermissions(roleId);
    checkedMenuKeys.value = res.data || [];
  } catch (error: any) {
    ElMessage.error(error.response?.data?.msg || '加载角色权限失败');
  }
};

// 保存权限
const savePermissions = async () => {
  try {
    const checkedKeys = menuTreeRef.value?.getCheckedKeys() as number[] || [];
    const halfCheckedKeys = menuTreeRef.value?.getHalfCheckedKeys() as number[] || [];
    const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys];

    await saveRolePermissions({
      roleId: currentRoleId.value,
      menuIds: allCheckedKeys
    });

    ElMessage.success('权限保存成功');
    permissionDialogVisible.value = false;
  } catch (error: any) {
    ElMessage.error(error.response?.data?.msg || '权限保存失败');
  }
};

// 删除角色
const handleDelete = async (row: Role) => {
  try {
    await ElMessageBox.confirm(`确定要删除角色 "${row.roleName}" 吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await deleteRole(row.roleId);
    ElMessage.success('删除成功');
    fetchRoles();
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.msg || '删除失败');
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择需要删除的角色');
    return;
  }

  try {
    const roleNames = multipleSelection.value.map(item => item.roleName).join('、');
    await ElMessageBox.confirm(`确定要批量删除选中的角色吗？\n${roleNames}`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const ids = multipleSelection.value.map(item => item.roleId);
    await deleteRole(ids);
    ElMessage.success('批量删除成功');
    fetchRoles();

    // 清空选择
    multipleTableRef.value?.clearSelection();
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.msg || '批量删除失败');
    }
  }
};
</script>

<style scoped>
.role-management-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 16px;
}

.table-header {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-tree) {
  max-height: 400px;
  overflow-y: auto;
}
</style>
